from django.shortcuts import render,HttpResponse
from app01.models import Userinfo
from flask import redirect


# Create your views here.
def index(request):
    return HttpResponse('成都东软学院')
def news(request):
    return render(request,'news.html')
def user(request):
    name='zhang'
    users=['zhao','qian','sun','li']
    return render(request,'user.html',{'n1':name,'n2':users})

def login(request):
    if request.method == 'GET':
        return render(request,'login.html')
    #elif request.method == "POST":
    username = request.POST.get('user')
    password = request.POST.get('pwd')
    user_list=Userinfo.objects.all()
    for obj in user_list:
        if obj.name ==username:
            if obj.password == password:
                return redirect("https://nsu.edu.cn")
            else:
                return render(request, 'login.html', {'error_msg': '账户密码错误'})
        return render(request, 'login.html', {'error_msg': '账户密码错误'})

    print(request.POST)
    print(username,password)
    if username == 'lin' and password == '123':
        return redirect("https://nsu.edu.cn")
    else:
        return render(request,'login.html',{'error_msg':'账户密码错误'})

def orm(request):
    # 增加数据
    # Userinfo.objects.create(name='zhao',password='123',age=12)
    # Userinfo.objects.create(name='qian', password='123', age=21)
    # Userinfo.objects.create(name='sun', password='123', age=22)
    # Userinfo.objects.create(name='li', password='123', age=23)

    # 删除数据
    # Userinfo.objects.filter(id = 12).delete()
    # Userinfo.objects.all().delete()

    # 查找数据
    # user_list =Userinfo.objects.all()
    # print(user_list)
    # for obj in user_list:
    #     print(obj.name,obj.password,obj.age)
    # user=Userinfo.objects.filter(id = 1).first
    # print(user.name,user.password,user.age)

    # 修改数据
    # Userinfo.objects.all().update(age=40)
    # Userinfo.objects.filter(name='zhao').update(age=18)

    return HttpResponse("登陆成功")


def user_list(request):
    user_list=Userinfo.objects.all()
    return render(request,'user_list.html',{'user_list':user_list})



def useradd(request):
    if request.method =='GET':
        return render(request,'user_add.html')

#     添加数据
    name=request.POST.get('name')
    password= request.POST.get('pwd')
    age = request.POST.get('age')

    Userinfo.objects.create(name=name,age=age,password=password)
    return redirect('/user_list/')

def user_del(request):
    nid=request.GET.get('nid')
    Userinfo.objects.filter(id=nid).delete()
    return redirect('/user_list/')

